﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using Projectmanagement.Utl;
using ProjectManagement.Models;
using Projectmanagement.Entity;


namespace Projectmanagement.Controllers
{
    [RoleRequired]
    public class ProjectController : Controller
    {

        public ActionResult Index()
        {
            return View();

        }

        [GridAction]
        public ActionResult _SelectIndex(int? conferenceid)
        {
            return View(new GridModel(DQ.GetProjects()));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _SaveAjaxEditing(int id, int? conferenceid)
        {
            var item = CH.GetDataByID<Project>(id);
            if (TryUpdateModel(item))
            {
                CH.Edit<Project>(item);
            }
            return View(new GridModel(DQ.GetProjects()));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _InsertAjaxEditing(int? conferenceid)
        {
            var item = new Project();

            if (TryUpdateModel(item))
            {
                CH.Create<Project>(item);
            }
            return View(new GridModel(DQ.GetProjects()));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _DeleteAjaxEditing(int id, int? conferenceid)
        {
            CH.Delete<Project>(id);
            return View(new GridModel(DQ.GetProjects()));
        }


        [GridAction]
        public ActionResult _SelectTaskIndex(int projectid)
        {
            return View(new GridModel(DQ.GetTasksSearch(projectid, "", 0, 0, "", true)));
        }

        public ActionResult GetImpTaskTpl(int? projectId, int? searchRole, string searchName)
        {
            _ImportModel import = new _ImportModel();
            var milestone = CH.GetDataByID<Milestone>(projectId);

            if (milestone != null)
            {
                import.ProjectID = milestone.Projectid;
            }
            else
            {
                import.ProjectID = projectId;
            }
            import.TemplateList = DQ.GetTaskTemplatesSearch(searchRole, searchName, milestone.MilestoneTemplateID);
            //ViewBag.Milestone = milestone.ID;
            ViewBag.namelist = (from x in CH.DB.Tasks
                                where x.ProjectID == milestone.Projectid
                                select x.Name).Distinct().ToList();

            return PartialView("ImpTaskTpl", import);
        }

        public ActionResult GetImpMilestoneTpl(int? projectId, int? searchRole, string searchName)
        {
            _ImportModel import = new _ImportModel();
            var milestone = CH.GetDataByID<Milestone>(projectId);

            if (milestone != null)
            {
                import.ProjectID = milestone.Projectid;
            }
            else
            {
                import.ProjectID = projectId;
            }
            import.TemplateList = DQ.GetTaskTemplatesSearch(searchRole, searchName, null);

            //ViewBag.namelist = (from x in CH.DB.Tasks
            //                    where x.ProjectID == milestone.Projectid
            //                    select x.Name).Distinct().ToList();

            return PartialView("ImpMilestoneTpl", import);
        }

        [GridAction]
        public ActionResult GetImpTaskTplSearch(int? projectId, int? searchRole, string searchName, string hidDefault, int? searchMilestone, string hidMilestone)
        {
            _ImportModel import = new _ImportModel();

            import.ProjectID = projectId;
            import.TemplateList = DQ.GetTaskTemplatesSearch(searchRole, searchName, searchMilestone);

            ViewBag.namelist = (from x in CH.DB.Tasks
                                where x.ProjectID == projectId
                                select x.Name).Distinct().ToList();




            return PartialView("ImpTaskTpl", import);
        }
        [HttpPost]
        public ActionResult ImportTaskTpl(_ImportModel model)
        {
            if (ModelState.IsValid)
            {
                string selTplStr = Request.Params["Templates"];

                if (selTplStr != null)
                {
                    var inprogresstaskstateid = CH.GetAllDatas<TaskState>().FirstOrDefault(f => f.Code == 30).ID;
                    List<string> selTplList = new List<string>();
                    selTplList = selTplStr.Split(',').ToList();
                    if (selTplList.Count > 0)
                    {
                        var project = CH.GetDataByID<Project>((int)model.ProjectID);
                        string projectCode = project.ProjectCode;
                        string prefix = projectCode;
                        Task task = new Task();

                        foreach (var selTpl in selTplList)
                        {
                            var ttpl = CH.GetDataByID<TaskTemplate>(int.Parse(selTpl));

                            var ttmilestone = new Milestone(); ;
                            var ttmilestonetemp = CH.GetDataByID<MilestoneTemplate>(ttpl.MilestoneID);

                            var members = CH.DB.Members.Where(w => w.ProjectID == model.ProjectID && w.RolePMID == ttpl.RolePMID).Select(x => x.Name);
                            var names = string.Join(",", members);

                            if (ttpl != null)
                            {
                                var milestone = DQ.GetMilestone().Where(w => w.Projectid == model.ProjectID && w.MilestoneTemplateID == ttmilestonetemp.ID).ToList();
                                //var milestone = DQ.GetMilestone().Where(w=>w.MilestoneTemplateID==ttmilestonetemp.ID).ToList();
                                if (milestone.Count == 0)
                                {
                                    ttmilestone.Projectid = model.ProjectID;
                                    ttmilestone.EndDate = project.EndDate.AddDays(ttmilestonetemp.DateCount);
                                    ttmilestone.MilestoneName = ttmilestonetemp.MilestoneName;
                                    ttmilestone.MilestoneTemplateID = ttmilestonetemp.ID;
                                    if (TryUpdateModel(ttmilestone))
                                    {
                                        CH.Create<Milestone>(ttmilestone);

                                    }
                                }

                                //去重复
                                var taskcount = CH.DB.Tasks.Where(x => x.ProjectID == model.ProjectID && x.Name == ttpl.Name).Count();
                                if (taskcount == 0)
                                {

                                    var records = CH.DB.Tasks.Where(s => s.TaskCode != null && s.TaskCode.StartsWith(prefix));
                                    if (records != null && records.Count() > 0)
                                    {
                                        string preCode = records.OrderByDescending(s => s.ID).First().TaskCode;
                                        task.TaskCode = prefix + string.Format("{0:D3}", Convert.ToInt32(preCode.Substring(preCode.Length - 3)) + 1);
                                    }
                                    else
                                    {
                                        task.TaskCode = prefix + "001";
                                    }
                                    task.Name = ttpl.Name;
                                    task.ProjectID = model.ProjectID;
                                    task.Owners = names;
                                    // task.EndDate = project.ConferenceStartDate.AddDays(ttpl.DateCount);
                                    task.EndDate = project.EndDate.AddDays(ttmilestonetemp.DateCount).AddDays(ttpl.DateCount);
                                    task.StartDate = task.EndDate.AddDays(-ttpl.Duration);
                                    task.TaskStateID = inprogresstaskstateid;
                                    task.Sequence = ttpl.Sequence;
                                    task.Content = ttpl.Content;
                                    task.KMLinks = ttpl.KMLinks;
                                    task.Deliverables = ttpl.Deliverables;
                                    task.Assinger = Employee.CurrentUserName;
                                    if (ttmilestone != null && ttmilestone.ID != 0)
                                    {
                                        task.MilestoneID = ttmilestone.ID;
                                    }
                                    //task.MilestoneID = ttpl.MilestoneID;
                                    CH.Create<Task>(task);
                                }
                            }


                            if (ttmilestonetemp != null)
                            {
                                ttmilestonetemp.Projectid = model.ProjectID;
                                if (TryUpdateModel(ttmilestonetemp))
                                {
                                    CH.Edit<MilestoneTemplate>(ttmilestonetemp);
                                }
                            }
                        }
                    }
                }
            }

            return RedirectToAction("Index");
            //return Json(new { Import = true});
        }

        [HttpPost]
        public PartialViewResult getprojects()
        {

            var data = from p in CH.DB.Projects where p.IsActived == true select p;

            if (Employee.CurrentRoleLVL == RoleLevel.Manager)
            {
                data = from p in data where p.Manager == Employee.CurrentUserName select p;
            }
            else if (Employee.CurrentRoleLVL < RoleLevel.Manager)
            {
                data = from p in data where p.Members.Any(a => a.Name == Employee.CurrentUserName) select p;
            }
            return PartialView("getprojects", data.Select(s => s.ProjectCode));
        }

        public JsonResult GetRole()
        {
            var member = from m in CH.DB.RolePMs
                         select m;
            var selectList = member.ToList().Select(a => new SelectListItem
            {
                Text = a.Name,
                Value = a.ID.ToString()
            });
            return Json(selectList, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult ImportTaskTplMilestone(_ImportModel model)
        {
            var milestone = CH.GetDataByID<Milestone>(model.ProjectID);
            var ttid = milestone.Projectid;
            if (ModelState.IsValid)
            {
                string selTplStr = Request.Params["Templates"];

                if (selTplStr != null)
                {
                    var inprogresstaskstateid = CH.GetAllDatas<TaskState>().FirstOrDefault(f => f.Code == 30).ID;
                    List<string> selTplList = new List<string>();
                    selTplList = selTplStr.Split(',').ToList();
                    if (selTplList.Count > 0)
                    {
                        var project = CH.GetDataByID<Project>((int)milestone.Projectid);
                        string projectCode = project.ProjectCode;
                        string prefix = projectCode;
                        Task task = new Task();

                        foreach (var selTpl in selTplList)
                        {
                            var ttpl = CH.GetDataByID<TaskTemplate>(int.Parse(selTpl));
                            var ttmilestone = CH.GetDataByID<Milestone>(ttpl.MilestoneID);

                            var members = CH.DB.Members.Where(w => w.ProjectID == milestone.Projectid && w.RolePMID == ttpl.RolePMID).Select(x => x.Name);
                            var names = string.Join(",", members);

                            if (ttpl != null)
                            {
                                //去重复
                                var taskcount = CH.DB.Tasks.Where(x => x.ProjectID == milestone.Projectid && x.Name == ttpl.Name).Count();
                                if (taskcount == 0)
                                {

                                    var records = CH.DB.Tasks.Where(s => s.TaskCode != null && s.TaskCode.StartsWith(prefix));
                                    if (records != null && records.Count() > 0)
                                    {
                                        string preCode = records.OrderByDescending(s => s.ID).First().TaskCode;
                                        task.TaskCode = prefix + string.Format("{0:D3}", Convert.ToInt32(preCode.Substring(preCode.Length - 3)) + 1);
                                    }
                                    else
                                    {
                                        task.TaskCode = prefix + "001";
                                    }
                                    task.Name = ttpl.Name;
                                    task.ProjectID = milestone.Projectid;
                                    task.Owners = names;
                                    if (ttmilestone == null)
                                    {
                                        task.EndDate = project.ConferenceStartDate.AddDays(ttpl.DateCount);
                                    }
                                    else
                                    {
                                        task.EndDate = ttmilestone.EndDate.AddDays(ttpl.DateCount);
                                    }
                                    task.StartDate = task.EndDate.AddDays(-ttpl.Duration);
                                    task.TaskStateID = inprogresstaskstateid;
                                    task.Sequence = ttpl.Sequence;
                                    task.Content = ttpl.Content;
                                    task.KMLinks = ttpl.KMLinks;
                                    task.Deliverables = ttpl.Deliverables;
                                    task.Assinger = Employee.CurrentUserName;
                                    task.MilestoneID = milestone.ID;
                                    CH.Create<Task>(task);
                                }
                            }
                            //if (ttmilestone != null)
                            //{

                            //    ttmilestone.Projectid = ttid;

                            //    if (TryUpdateModel(ttmilestone))
                            //    {
                            //        CH.Edit<Milestone>(ttmilestone);
                            //    }
                            //}
                        }
                    }
                }
            }

            return RedirectToAction("Index");
            //return Json(new { Import = true});
        }
    }
}
